/**
 * Created by niexiaosong on 18/7/13.
 */

var jgbm = "";
var jsdm = "";
$(document).ready(function () {
    var jgLoading = {"name" : "加载中..."};
    $.fn.zTree.init($("#tree_jg"), setting, jgLoading);
    getJgTree();
    //角色列表
    queryRoleList();
    fuzzySearch('tree_jg', '#key', null, true); //初始化模糊搜索方法
    //当前机构
    getJgbm();

});

//**********************左侧树形开始
var setting = {
    view: {
        addHoverDom: addHoverDom,
        removeHoverDom: removeHoverDom,
        selectedMulti: false,
        showIcon:false

    },
    data: {
        simpleData: {
            enable: true
        }
    },
    callback: {
        onClick: jgTreeOnClick,
        onExpand: zTreeOnExpand
    }

};

var zNodes_jg = [{}];

//***********************左侧树形end
//****************机构权限设置 树形 start
var setting_jgqx = {
    check: {
        enable: true
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    view: {
        showIcon: false
    }
};

//****************机构权限设置 树形 start
var setting_gnqx = {
    check: {
        enable: true
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    view: {
        showIcon: false
    }
};

var  setting_sjqx = {
    check: {
        enable: true
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    view: {
        showIcon: false
    }
};

var zNodes_gnqx = [];
var zNodes_sjqx = [];
//****************机构权限设置 树形end


var zNodes_jgqx = [];
//****************机构权限设置 树形end

//***************************ztree 点击样式 *************
var newCount = 1;
function addHoverDom(treeId, treeNode) {
    var sObj = $("#" + treeNode.tId + "_span");
    if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='add node' onfocus='this.blur();'></span>";
    sObj.after(addStr);
    var btn = $("#addBtn_" + treeNode.tId);
    if (btn) btn.bind("click",
        function () {
            var zTree = $.fn.zTree.getZTreeObj("tree_jg");
            zTree.addNodes(treeNode, {
                id: (100 + newCount),
                pId: treeNode.id,
                name: "new node" + (newCount++)
            });
            return false;
        });
}
;
function removeHoverDom(treeId, treeNode) {
    $("#addBtn_" + treeNode.tId).unbind().remove();
}
;

//***************************ztree 点击样式 *************


//*******************************表格 start******************

function showTable() {
    var jsmc = $.trim($("#jsmc").val());
    var data =  {'jsmc': jsmc,'jgbm': jgbm};
    $.ajax({
        success: function (jsonData) {
            if (jsonData.code == 200) {   //查询成功
                showTable(jsonData.list);
                Common.qxGnan();
                jsdm = "";
            } else {

            }
        }
    });
    var columnList = [
        {
            field: 'jsmc',
            title: '角色名称',
            align: 'left',
            halign: 'left',
            valign: 'middle',
            width: '200'

        },
        {
            field: 'jsms',
            title: '角色描述',
            align: 'left',
            halign: 'left',
            valign: 'middle',
            width: '180'
        },
        {
            field: 'jsdm',
            title: '操作',
            align: 'left',
            halign: 'left',
            valign: 'middle',
            width: '100',
            formatter: function (value, row) {
                return '<div>' +
                    '<span class="systemroleedit"><a class="blue" href="#" onclick="LayerWn.openDialog(\'修改角色\',baseURL + \'plat-edit-role.html?jsdm=' + value + '\',450,300,queryRoleList())">' +
                    '<i class="btn-eidt-wn" style="font-size: 125%" title="修改"></i></a></span>' +
                    '<a class="red" href="#" onclick="delrole(\'' + value + '\')">' +
                    '<i class="btn-del-wn" style="font-size: 125%" title="删除"></i></a>' +
                   // '<a class="blue" href="#" onclick="setRole(\'' + value + '\')">' +
                   // '<i class="btn-view-wn" style="font-size: 125%" title="角色设置"></i></a>' +
                    '</div>';
            }
        }];

    $("#tb1").bootstrapTable('destroy').bootstrapTable({
        method: "POST",
        contentType: 'application/json',
        dataType: "json",
        url: "role/rolelist",
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        sortable: false,                     //是否启用排序
        clickToSelect: true,                //是否启用点击选中行
        height:$(document).height() - 100,
        onClickRow: function (row, element, field) {
            $('.info').removeClass('info');//去除之前选中的行的，选中样式
            $(element).addClass('info');//添加当前选中的 success样式用于区别
            jsdm = row.jsdm;
            getGnqxTree();//功能权限获取
           // getSjqxTree();//数据权限获取

        },

        columns: columnList,
        pagination: true,                   //是否显示分页（*）
        //每页的记录行数（*）
        pageSize: 10,
        //可供选择的每页的行数（*）
        pageList: [10, 25, 50, 100],
        sidePagination:"server",
        queryParamsType:"",
        queryParams:function queryParams(params){
            var param = data;
            var PageBean = {
                pageNo : params.pageNumber,
                pageSize : params.pageSize,
                totalRecord : 0 ,
                totalPage : 0,
                results : []
                // orderColumn : 'order by t1.cjsj desc'
            }

            param.page = PageBean;
            param = JSON.stringify(param);
            return param;
        }
    });
}
//*******************************表格  end*******************



/**
 * 根据条件查询角色列表
 */
function queryRoleList() {
    showTable();
}

/**
 * 删除角色
 */
function delrole(jsdm) {

    LayerWn.showConfirm("确定要删除吗？",function () {
        $.ajax({
            type: "DELETE",
            contentType: 'application/json',
            dataType: "json",
            url: "role/delrole/" + jsdm,
            success: function (jsonData) {
                if (jsonData.code == 200) {
                    LayerWn.showSucAlert('删除成功');
                    setTimeout(function () {
                        parent.layer.closeAll()
                    }, 1000);
                    queryRoleList();
                } else {

                }
            }
        });
    });
}

/**
 * 定义树节点展开事件，查询子节点
 * @param event
 * @param treeId
 * @param treeNode
 */
function zTreeOnExpand(event, treeId, treeNode){
    queryChildrenList(treeNode);
}

/**
 * 查询子节点
 * @param treeNode
 */
function queryChildrenList(treeNode){
    var jgmc = $("#key").val();
    if(jgmc != '' || treeNode.children != undefined){
        return;
    }
    var queryParms = {
        pid : treeNode.id,
        jgmc : jgmc
    };
    $.ajax({
        type: "GET",
        contentType: 'application/json',
        dataType: "json",
        url: "commonapi/findjgtreeByPid",
        data: queryParms,
        success:function(data){
            //添加子节点到指定的父节点
            //var jsondata= eval(data.jgTreeList);
            var jsondata= data.jgTreeList;
            for(var i=0;i<jsondata.length;i++){
                if(jsondata[i].isLeaf != '1'){
                    jsondata[i].isParent = true;
                }
            }
            if(jsondata != null && jsondata != ""){
                var treeObj = $.fn.zTree.getZTreeObj("tree_jg");
                var parentZNode = treeObj.getNodeByParam("id", treeNode.id, null);
                treeObj.addNodes(parentZNode,jsondata, false);
            }
        },
        error: function () {
            alert('请求失败');
        }
    });
}


/**
 * 获取当前机构树形
 */
function getJgTree() {
    $.ajax({
        type: "GET",
        contentType: 'application/json',
        dataType: "json",
        url: "commonapi/findjgtree",
        success: function (jsonData) {
            if (jsonData.code == 200) {
                var jgTreeList = jsonData.jgTreeList;
                for(var i=0;i<jgTreeList.length;i++){
                    if(jgTreeList[i].isLeaf != '1'){
                        jgTreeList[i].isParent = true;
                    }
                }

                $.fn.zTree.init($("#tree_jg"), setting, jsonData.jgTreeList);
                var treeObj = $.fn.zTree.getZTreeObj("tree_jg");
                var nodes = treeObj.getNodes();
                if (nodes.length>0) {
                    /*//默认展开二级节点
                    if(nodes[0].children.length>0){
                        nodes=nodes[0].children;
                    }*/
                    treeObj.expandNode(nodes[0], true, false, false);
                    //默认选中根节点
                    treeObj.selectNode(treeObj.getNodes()[0]);
                    getGnqxTree();//功能权限获取
                    //getSjqxTree();//数据权限获取
                }
            } else {
            }
        }
    });
}


/**
 * 机构树形选中
 */

function jgTreeOnClick(event, treeId, treeNode, clickFlag) {
    $("input[type=checkbox]").each(function(){
        $(this).attr("disabled",false);
    });
    jgbm = treeNode.id;
    queryRoleList();
   // getJgqxByJgbm(treeNode.id);
    getGnqxTree();//功能权限获取
    //getSjqxTree();//数据权限获取
}

/**
 * 获取当前机构编码
 */
function getJgbm() {
    $.ajax({
        type: "GET",
        contentType: 'application/json',
        dataType: "json",
        url: "commonapi/jgbm",
        success: function (jsonData) {
            if (jsonData.code == 200) {
                jgbm = jsonData.jgbm;
            }
        }
    });
}


//新增
function  addRole() {
    LayerWn.openDialog('新增角色',baseURL + 'plat-add-role.html?jgbm='+ jgbm,350,320);
}
//角色复制弹出层
function copyRole() {
    LayerWn.openDialog('角色复制',baseURL + 'plat-copy-role.html?jgbm=' + jgbm, 790, 580);
}

 // 获取当前机构权限
 function getZcjgQx()
 {
     $.ajax({
         type: "GET",
         contentType: 'application/json',
         dataType: "json",
         url: "role/getzcjgqx",
         success: function (jsonData) {
             if (jsonData.code == 200) {
                 var list = jsonData.sysGncdList;
                 var divhtml = '<div class="hr-line-dashed"></div>';
                 if(list.length >0){
                     for (var i = 0; i < list.length; i++) {
                         var data = list[i];
                              divhtml += '<div class="checkbox i-checks">';
                              divhtml +='<label><input type="checkbox" disabled=""  name="jgqxname" value="'+data.mcode+'"><i></i>'+data.mcaption+'</label>';
                              divhtml +='</div>';
                     }
                 }
                 $('#jsqxdiv').append(divhtml);
                 showCheckCss();
             }
         }
     });

 }



 //复选样式
  function showCheckCss()
  {

      $('.i-checks').iCheck({
          checkboxClass: 'icheckbox_square-green',
          radioClass: 'iradio_square-green',
      });
  }
//清空复选框
function selectNull(){
    $("input[name='jgqxname']").each(function(){
        this.checked = false;
    });
    showCheckCss();
}


//角色设置页面
function setRole(jsdm)
{
    $.ajax({
        type: "GET",
        contentType: 'application/json',
        dataType: "json",
        url: "role/getzcjgqxbyjgbm/"+jgbm,
        success: function (jsonData) {
            if (jsonData.code == 200) {   //查询成
                if(jsonData.sysGncdList.length>0)
                {
                    LayerWn.openDialog('角色设置','plat-set-role.html?jsdm=' + jsdm + '&jgbm='+jgbm,440,540);
                }else{
                    LayerWn.showFailAlert("请先设置机构权限");
                }
            }
        }
    });

}


//复制角色权限
function copyJgqx()
{
    LayerWn.openDialog('角色复制', 'plat-copy-jgqx.html?jgbm=' + jgbm, 1000, 500);
}


/**
 * 获取菜单树--功能权限使用-数据权限使用
 */
function getGnqxTree() {

    if(jgbm!=undefined && jgbm !=""){
        $.ajax({
            type: "GET",
            contentType: 'application/json',
            dataType: "json",
            url: "role/getmenutree/"+jgbm,
            success: function (jsonData) {
                if (jsonData.code == 200) {
                    $.fn.zTree.init($("#tree_gnqx"), setting_gnqx, jsonData.menuTreeList);
                    getGnqxCheck();
                } else {
                }
            }
        });
    }
}

//保存  功能权限 or 数据权限
function save() {
    var type = $(".nav-tabs li.active").attr("id");

    if(jsdm == null || jsdm == ""){
        LayerWn.showAlert('请先选择一个角色!');
        return;
    }

    if("gnqx"==type)
    {
        //保存功能权限
        saveGnqxRole(jgbm,jsdm);
    }else if("sjqx"==type)
    {
        //保存数据权限
        saveSjqx(jgbm,jsdm);
    }
}
//保存功能权限设置
function saveGnqxRole(jgbm,jsdm)
{

    if(validate(onCheckGnqxZtree()))
    {
        $("#saveBtn").attr('disabled',true);
        $.ajax({
            type: "POST",
            contentType: 'application/x-www-form-urlencoded',
            dataType: "json",
            url: "role/savegnqx",
            data:
            {
                ztreeCheckList:onCheckGnqxZtree(),
                jgbm:jgbm,
                jsdm:jsdm
            },
            success: function (jsonData) {
                if (jsonData.code == 200) {   //查询成功
                    LayerWn.showSucAlert("保存成功");
                    LayerWn.closeDialog();
                    $("#saveBtn").removeAttr('disabled');
                }
            }
        });
    }
}
//获取功能权限 选中
function onCheckGnqxZtree() {
    var treeObj = $.fn.zTree.getZTreeObj("tree_gnqx"),
        nodes = treeObj.getCheckedNodes(true),
        v = "";
    for (var i = 0; i < nodes.length; i++) {
        v += nodes[i].id + ",";
    }
    return v;
}
//功能权限提交前校验
function validate(check_val){

    if(check_val.length==0)
    {
        LayerWn.showAlert('请选功能权限!');
        return false;
    }
    return true;
}
//获取功能权限已有数据 并 默认选中
function getGnqxCheck()
{
    $.ajax({
        type: "GET",
        contentType: 'application/json',
        dataType: "json",
        url: "role/getGnqxCheck",
        data:
        {
            jgbm:jgbm,
            jsdm:jsdm
        },
        success: function (jsonData) {
            if (jsonData.code == 200) {   //查询成功
                var list = jsonData.sysGnqxCheckList;
                var treeObj = $.fn.zTree.getZTreeObj("tree_gnqx");
                if(list.length >0){
                    for (var i = 0; i < list.length; i++) {
                        var data = list[i];

                            var node = treeObj.getNodeByParam("id", data.cddm, null);
                        if(node != null) {
                            //treeObj.expandNode(node, true, false, false);
                            treeObj.checkNode(node, true, false);
                        }
                    }
                }
            }
        }
    });
}

/**
 * 获取数据权限-根据机构编码
 */
function getSjqxTree() {

    if(jgbm!=undefined && jgbm !="")
    $.ajax({
        type: "GET",
        contentType: 'application/json',
        dataType: "json",
        url: "role/getSjqxTree/"+jgbm,
        success: function (jsonData) {
            if (jsonData.code == 200) {
                 $.fn.zTree.init($("#tree_sjqx"), setting_sjqx, jsonData.sjqxTreeList);
                 getSjqxCheck();
            } else {
            }
        }
    });
}

//保存数据权限设置
function saveSjqx(jgbm,jsdm)
{

    if(validatesSjqx(onCheckSjqxZtree()))
    {
        $("#saveBtn").attr('disabled',true);
        $.ajax({
            type: "POST",
            contentType: 'application/x-www-form-urlencoded',
            dataType: "json",
            url: "role/savesjqx",
            data:
            {
                ztreeCheckList:onCheckSjqxZtree(),
                jgbm:jgbm,
                jsdm:jsdm
            },
            success: function (jsonData) {
                $("#saveBtn").removeAttr('disabled');
                if (jsonData.code == 200) {   //查询成功
                    LayerWn.showSucAlert("保存成功");
                    LayerWn.closeDialog();
                }
            }
        });
    }
}
//功能权限提交前校验
function validatesSjqx(check_val){

    // TODO 数据权限暂时先去掉--目前这块功能还没用起来
    /*if(check_val.length==0)
    {
        LayerWn.showAlert('请选数据权限!');
        return false;
    }*/
    return true;
}
//获取数据权限 选中  只取下级数据
function onCheckSjqxZtree() {
    var treeObj = $.fn.zTree.getZTreeObj("tree_sjqx"),
        nodes = treeObj.getCheckedNodes(true),
        v = "";
    for (var i = 0; i < nodes.length; i++) {
        if(nodes[i].pId!=null)
        {
            v += nodes[i].id + ",";
        }
    }
    return v;
}

//获取数据权限已有数据 并 默认选中
function getSjqxCheck()
{
    $.ajax({
        type: "GET",
        contentType: 'application/json',
        dataType: "json",
        url: "role/getSjqxCheck",
        data:
        {
            jgbm:jgbm,
            jsdm:jsdm
        },
        success: function (jsonData) {
            if (jsonData.code == 200) {   //查询成功
                var list = jsonData.sysSjqxCheckList;
                var treeObj = $.fn.zTree.getZTreeObj("tree_sjqx");
                if(list.length >0){
                    for (var i = 0; i < list.length; i++) {
                        var data = list[i];

                            var node = treeObj.getNodeByParam("id", data.gnsjdm, null);
                        if(node !=null) {
                            treeObj.expandNode(node, true, true, true);
                            treeObj.checkNode(node, true, false);
                        }
                    }
                }
            }
        }
    });
}